#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/24
# @Author  : YunZhen
# @File    : init_device.py
# @Software: PyCharm
"""
设备初始化脚本
"""
import json
import adbutils
import subprocess
import uiautomator2 as u2
from loguru import logger
from utils.venv_check import check_environment


def init_device(device=None):
    """初始化设备连接"""
    print("=== 设备初始化: 尝试连接设备 === \n")
    if not check_environment():
        raise EnvironmentError("环境配置有误，请检查后重试。")

    try:
        # 检查设备连接
        if device is None:
            devices = adbutils.AdbClient().list()
            if not devices:
                raise RuntimeError("未检测到连接的设备，请确保设备已通过USB连接并开启USB调试模式。")
            device = devices[0].serial
            logger.info(f"自动选择设备: {device}")
        logger.debug(f'正在连接设备{device}...')
        phone = u2.connect(device)
        logger.info(f"成功连接设备: {phone.info.get('productName', device)}")
        logger.debug(f"设备配置:\n {json.dumps(phone.info, ensure_ascii=False, indent=2)}")
        return phone
    except Exception as e:
        logger.warning(f"设备连接失败: {e}")
        # 尝试重启ADB服务
        subprocess.run(['adb', 'kill-server'])
        subprocess.run(['adb', 'start-server'])
        raise e
